home *** CD-ROM | disk | FTP | other *** search
/ Risc World 5 / Risc World 5.iso / SOFTWARE / Issue5 / PD / DIRSYNC / LegalStuff / gnudiff / analyze.c next >
C/C++ Source or Header  |  2004-12-19  |  31KB  |  1,085 lines

  1. /* Analyze file differences for GNU DIFF.
  2.  
  3.    Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1998, 2001, 2002
  4.    Free Software Foundation, Inc.
  5.  
  6.    This file is part of GNU DIFF.
  7.  
  8.    GNU DIFF is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 2, or (at your option)
  11.    any later version.
  12.  
  13.    GNU DIFF is distributed in the hope that it will be useful,
  14.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.    GNU General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License
  19.    along with this program; see the file COPYING.
  20.    If not, write to the Free Software Foundation,
  21.    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
  22.  
  23. /* The basic algorithm is described in:
  24.    "An O(ND) Difference Algorithm and its Variations", Eugene Myers,
  25.    Algorithmica Vol. 1 No. 2, 1986, pp. 251-266;
  26.    see especially section 4.2, which describes the variation used below.
  27.    Unless the --minimal option is specified, this code uses the TOO_EXPENSIVE
  28.    heuristic, by Paul Eggert, to limit the cost to O(N**1.5 log N)
  29.    at the price of producing suboptimal output for large inputs with
  30.    many differences.
  31.  
  32.    The basic algorithm was independently discovered as described in:
  33.    "Algorithms for Approximate String Matching", E. Ukkonen,
  34.    Information and Control Vol. 64, 1985, pp. 100-118.  */
  35.  
  36. #include "diff.h"
  37. #include <cmpbuf.h>
  38. #include <error.h>
  39. #include <regex.h>
  40. #include <xalloc.h>
  41. #include <limits.h>
  42.  
  43. static lin *xvec, *yvec;    /* Vectors being compared. */
  44. static lin *fdiag;        /* Vector, indexed by diagonal, containing
  45.                    1 + the X coordinate of the point furthest
  46.                    along the given diagonal in the forward
  47.                    search of the edit matrix. */
  48. static lin *bdiag;        /* Vector, indexed by diagonal, containing
  49.                    the X coordinate of the point furthest
  50.                    along the given diagonal in the backward
  51.                    search of the edit matrix. */
  52. static lin too_expensive;    /* Edit scripts longer than this are too
  53.                    expensive to compute.  */
  54.  
  55. #define SNAKE_LIMIT 20    /* Snakes bigger than this are considered `big'.  */
  56.  
  57. struct partition
  58. {
  59.   lin xmid, ymid;    /* Midpoints of this partition.  */
  60.   bool lo_minimal;    /* Nonzero if low half will be analyzed minimally.  */
  61.   bool hi_minimal;    /* Likewise for high half.  */
  62. };
  63.  
  64. /* Find the midpoint of the shortest edit script for a specified
  65.    portion of the two files.
  66.  
  67.    Scan from the beginnings of the files, and simultaneously from the ends,
  68.    doing a breadth-first search through the space of edit-sequence.
  69.    When the two searches meet, we have found the midpoint of the shortest
  70.    edit sequence.
  71.  
  72.    If FIND_MINIMAL is nonzero, find the minimal edit script regardless
  73.    of expense.  Otherwise, if the search is too expensive, use
  74.    heuristics to stop the search and report a suboptimal answer.
  75.  
  76.    Set PART->(xmid,ymid) to the midpoint (XMID,YMID).  The diagonal number
  77.    XMID - YMID equals the number of inserted lines minus the number
  78.    of deleted lines (counting only lines before the midpoint).
  79.    Return the approximate edit cost; this is the total number of
  80.    lines inserted or deleted (counting only lines before the midpoint),
  81.    unless a heuristic is used to terminate the search prematurely.
  82.  
  83.    Set PART->lo_minimal to true iff the minimal edit script for the
  84.    left half of the partition is known; similarly for PART->hi_minimal.
  85.  
  86.    This function assumes that the first lines of the specified portions
  87.    of the two files do not match, and likewise that the last lines do not
  88.    match.  The caller must trim matching lines from the beginning and end
  89.    of the portions it is going to specify.
  90.  
  91.    If we return the "wrong" partitions,
  92.    the worst this can do is cause suboptimal diff output.
  93.    It cannot cause incorrect diff output.  */
  94.  
  95. static lin
  96. diag (lin xoff, lin xlim, lin yoff, lin ylim, bool find_minimal,
  97.       struct partition *part)
  98. {
  99.   lin *const fd = fdiag;    /* Give the compiler a chance. */
  100.   lin *const bd = bdiag;    /* Additional help for the compiler. */
  101.   lin const *const xv = xvec;    /* Still more help for the compiler. */
  102.   lin const *const yv = yvec;    /* And more and more . . . */
  103.   lin const dmin = xoff - ylim;    /* Minimum valid diagonal. */
  104.   lin const dmax = xlim - yoff;    /* Maximum valid diagonal. */
  105.   lin const fmid = xoff - yoff;    /* Center diagonal of top-down search. */
  106.   lin const bmid = xlim - ylim;    /* Center diagonal of bottom-up search. */
  107.   lin fmin = fmid, fmax = fmid;    /* Limits of top-down search. */
  108.   lin bmin = bmid, bmax = bmid;    /* Limits of bottom-up search. */
  109.   lin c;            /* Cost. */
  110.   bool odd = (fmid - bmid) & 1;    /* True if southeast corner is on an odd
  111.                    diagonal with respect to the northwest. */
  112.  
  113.   fd[fmid] = xoff;
  114.   bd[bmid] = xlim;
  115.  
  116.   for (c = 1;; ++c)
  117.     {
  118.       lin d;            /* Active diagonal. */
  119.       bool big_snake = 0;
  120.  
  121.       /* Extend the top-down search by an edit step in each diagonal. */
  122.       fmin > dmin ? fd[--fmin - 1] = -1 : ++fmin;
  123.       fmax < dmax ? fd[++fmax + 1] = -1 : --fmax;
  124.       for (d = fmax; d >= fmin; d -= 2)
  125.     {
  126.       lin x, y, oldx, tlo = fd[d - 1], thi = fd[d + 1];
  127.  
  128.       if (tlo >= thi)
  129.         x = tlo + 1;
  130.       else
  131.         x = thi;
  132.       oldx = x;
  133.       y = x - d;
  134.       while (x < xlim && y < ylim && xv[x] == yv[y])
  135.         ++x, ++y;
  136.       if (x - oldx > SNAKE_LIMIT)
  137.         big_snake = 1;
  138.       fd[d] = x;
  139.       if (odd && bmin <= d && d <= bmax && bd[d] <= x)
  140.         {
  141.           part->xmid = x;
  142.           part->ymid = y;
  143.           part->lo_minimal = part->hi_minimal = 1;
  144.           return 2 * c - 1;
  145.         }
  146.     }
  147.  
  148.       /* Similarly extend the bottom-up search.  */
  149.       bmin > dmin ? bd[--bmin - 1] = LIN_MAX : ++bmin;
  150.       bmax < dmax ? bd[++bmax + 1] = LIN_MAX : --bmax;
  151.       for (d = bmax; d >= bmin; d -= 2)
  152.     {
  153.       lin x, y, oldx, tlo = bd[d - 1], thi = bd[d + 1];
  154.  
  155.       if (tlo < thi)
  156.         x = tlo;
  157.       else
  158.         x = thi - 1;
  159.       oldx = x;
  160.       y = x - d;
  161.       while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1])
  162.         --x, --y;
  163.       if (oldx - x > SNAKE_LIMIT)
  164.         big_snake = 1;
  165.       bd[d] = x;
  166.       if (!odd && fmin <= d && d <= fmax && x <= fd[d])
  167.         {
  168.           part->xmid = x;
  169.           part->ymid = y;
  170.           part->lo_minimal = part->hi_minimal = 1;
  171.           return 2 * c;
  172.         }
  173.     }
  174.  
  175.       if (find_minimal)
  176.     continue;
  177.  
  178.       /* Heuristic: check occasionally for a diagonal that has made
  179.      lots of progress compared with the edit distance.
  180.      If we have any such, find the one that has made the most
  181.      progress and return it as if it had succeeded.
  182.  
  183.      With this heuristic, for files with a constant small density
  184.      of changes, the algorithm is linear in the file size.  */
  185.  
  186.       if (200 < c && big_snake && speed_large_files)
  187.     {
  188.       lin best;
  189.  
  190.       best = 0;
  191.       for (d = fmax; d >= fmin; d -= 2)
  192.         {
  193.           lin dd = d - fmid;
  194.           lin x = fd[d];
  195.           lin y = x - d;
  196.           lin v = (x - xoff) * 2 - dd;
  197.           if (v > 12 * (c + (dd < 0 ? -dd : dd)))
  198.         {
  199.           if (v > best
  200.               && xoff + SNAKE_LIMIT <= x && x < xlim
  201.               && yoff + SNAKE_LIMIT <= y && y < ylim)
  202.             {
  203.               /* We have a good enough best diagonal;
  204.              now insist that it end with a significant snake.  */
  205.               int k;
  206.  
  207.               for (k = 1; xv[x - k] == yv[y - k]; k++)
  208.             if (k == SNAKE_LIMIT)
  209.               {
  210.                 best = v;
  211.                 part->xmid = x;
  212.                 part->ymid = y;
  213.                 break;
  214.               }
  215.             }
  216.         }
  217.         }
  218.       if (best > 0)
  219.         {
  220.           part->lo_minimal = 1;
  221.           part->hi_minimal = 0;
  222.           return 2 * c - 1;
  223.         }
  224.  
  225.       best = 0;
  226.       for (d = bmax; d >= bmin; d -= 2)
  227.         {
  228.           lin dd = d - bmid;
  229.           lin x = bd[d];
  230.           lin y = x - d;
  231.           lin v = (xlim - x) * 2 + dd;
  232.           if (v > 12 * (c + (dd < 0 ? -dd : dd)))
  233.         {
  234.           if (v > best
  235.               && xoff < x && x <= xlim - SNAKE_LIMIT
  236.               && yoff < y && y <= ylim - SNAKE_LIMIT)
  237.             {
  238.               /* We have a good enough best diagonal;
  239.              now insist that it end with a significant snake.  */
  240.               int k;
  241.  
  242.               for (k = 0; xv[x + k] == yv[y + k]; k++)
  243.             if (k == SNAKE_LIMIT - 1)
  244.               {
  245.                 best = v;
  246.                 part->xmid = x;
  247.                 part->ymid = y;
  248.                 break;
  249.               }
  250.             }
  251.         }
  252.         }
  253.       if (best > 0)
  254.         {
  255.           part->lo_minimal = 0;
  256.           part->hi_minimal = 1;
  257.           return 2 * c - 1;
  258.         }
  259.     }
  260.  
  261.       /* Heuristic: if we've gone well beyond the call of duty,
  262.      give up and report halfway between our best results so far.  */
  263.       if (c >= too_expensive)
  264.     {
  265.       lin fxybest, fxbest;
  266.       lin bxybest, bxbest;
  267.  
  268.       fxbest = bxbest = 0;  /* Pacify `gcc -Wall'.  */
  269.  
  270.       /* Find forward diagonal that maximizes X + Y.  */
  271.       fxybest = -1;
  272.       for (d = fmax; d >= fmin; d -= 2)
  273.         {
  274.           lin x = MIN (fd[d], xlim);
  275.           lin y = x - d;
  276.           if (ylim < y)
  277.         x = ylim + d, y = ylim;
  278.           if (fxybest < x + y)
  279.         {
  280.           fxybest = x + y;
  281.           fxbest = x;
  282.         }
  283.         }
  284.  
  285.       /* Find backward diagonal that minimizes X + Y.  */
  286.       bxybest = LIN_MAX;
  287.       for (d = bmax; d >= bmin; d -= 2)
  288.         {
  289.           lin x = MAX (xoff, bd[d]);
  290.           lin y = x - d;
  291.           if (y < yoff)
  292.         x = yoff + d, y = yoff;
  293.           if (x + y < bxybest)
  294.         {
  295.           bxybest = x + y;
  296.           bxbest = x;
  297.         }
  298.         }
  299.  
  300.       /* Use the better of the two diagonals.  */
  301.       if ((xlim + ylim) - bxybest < fxybest - (xoff + yoff))
  302.         {
  303.           part->xmid = fxbest;
  304.           part->ymid = fxybest - fxbest;
  305.           part->lo_minimal = 1;
  306.           part->hi_minimal = 0;
  307.         }
  308.       else
  309.         {
  310.           part->xmid = bxbest;
  311.           part->ymid = bxybest - bxbest;
  312.           part->lo_minimal = 0;
  313.           part->hi_minimal = 1;
  314.         }
  315.       return 2 * c - 1;
  316.     }
  317.     }
  318. }
  319.  
  320. /* Compare in detail contiguous subsequences of the two files
  321.    which are known, as a whole, to match each other.
  322.  
  323.    The results are recorded in the vectors files[N].changed, by
  324.    storing 1 in the element for each line that is an insertion or deletion.
  325.  
  326.    The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
  327.  
  328.    Note that XLIM, YLIM are exclusive bounds.
  329.    All line numbers are origin-0 and discarded lines are not counted.
  330.  
  331.    If FIND_MINIMAL, find a minimal difference no matter how
  332.    expensive it is.  */
  333.  
  334. static void
  335. compareseq (lin xoff, lin xlim, lin yoff, lin ylim, bool find_minimal)
  336. {
  337.   lin * const xv = xvec; /* Help the compiler.  */
  338.   lin * const yv = yvec;
  339.  
  340.   /* Slide down the bottom initial diagonal. */
  341.   while (xoff < xlim && yoff < ylim && xv[xoff] == yv[yoff])
  342.     ++xoff, ++yoff;
  343.   /* Slide up the top initial diagonal. */
  344.   while (xlim > xoff && ylim > yoff && xv[xlim - 1] == yv[ylim - 1])
  345.     --xlim, --ylim;
  346.  
  347.   /* Handle simple cases. */
  348.   if (xoff == xlim)
  349.     while (yoff < ylim)
  350.       files[1].changed[files[1].realindexes[yoff++]] = 1;
  351.   else if (yoff == ylim)
  352.     while (xoff < xlim)
  353.       files[0].changed[files[0].realindexes[xoff++]] = 1;
  354.   else
  355.     {
  356.       lin c;
  357.       struct partition part;
  358.  
  359.       /* Find a point of correspondence in the middle of the files.  */
  360.  
  361.       c = diag (xoff, xlim, yoff, ylim, find_minimal, &part);
  362.  
  363.       if (c == 1)
  364.     {
  365.       /* This should be impossible, because it implies that
  366.          one of the two subsequences is empty,
  367.          and that case was handled above without calling `diag'.
  368.          Let's verify that this is true.  */
  369.       abort ();
  370. #if 0
  371.       /* The two subsequences differ by a single insert or delete;
  372.          record it and we are done.  */
  373.       if (part.xmid - part.ymid < xoff - yoff)
  374.         files[1].changed[files[1].realindexes[part.ymid - 1]] = 1;
  375.       else
  376.         files[0].changed[files[0].realindexes[part.xmid]] = 1;
  377. #endif
  378.     }
  379.       else
  380.     {
  381.       /* Use the partitions to split this problem into subproblems.  */
  382.       compareseq (xoff, part.xmid, yoff, part.ymid, part.lo_minimal);
  383.       compareseq (part.xmid, xlim, part.ymid, ylim, part.hi_minimal);
  384.     }
  385.     }
  386. }
  387.  
  388. /* Discard lines from one file that have no matches in the other file.
  389.  
  390.    A line which is discarded will not be considered by the actual
  391.    comparison algorithm; it will be as if that line were not in the file.
  392.    The file's `realindexes' table maps virtual line numbers
  393.    (which don't count the discarded lines) into real line numbers;
  394.    this is how the actual comparison algorithm produces results
  395.    that are comprehensible when the discarded lines are counted.
  396.  
  397.    When we discard a line, we also mark it as a deletion or insertion
  398.    so that it will be printed in the output.  */
  399.  
  400. static void
  401. discard_confusing_lines (struct file_data filevec[])
  402. {
  403.   int f;
  404.   lin i;
  405.   char *discarded[2];
  406.   lin *equiv_count[2];
  407.   lin *p;
  408.  
  409.   /* Allocate our results.  */
  410.   p = xmalloc ((filevec[0].buffered_lines + filevec[1].buffered_lines)
  411.            * (2 * sizeof *p));
  412.   for (f = 0; f < 2; f++)
  413.     {
  414.       filevec[f].undiscarded = p;  p += filevec[f].buffered_lines;
  415.       filevec[f].realindexes = p;  p += filevec[f].buffered_lines;
  416.     }
  417.  
  418.   /* Set up equiv_count[F][I] as the number of lines in file F
  419.      that fall in equivalence class I.  */
  420.  
  421.   p = zalloc (filevec[0].equiv_max * (2 * sizeof *p));
  422.   equiv_count[0] = p;
  423.   equiv_count[1] = p + filevec[0].equiv_max;
  424.  
  425.   for (i = 0; i < filevec[0].buffered_lines; ++i)
  426.     ++equiv_count[0][filevec[0].equivs[i]];
  427.   for (i = 0; i < filevec[1].buffered_lines; ++i)
  428.     ++equiv_count[1][filevec[1].equivs[i]];
  429.  
  430.   /* Set up tables of which lines are going to be discarded.  */
  431.  
  432.   discarded[0] = zalloc (filevec[0].buffered_lines
  433.              + filevec[1].buffered_lines);
  434.   discarded[1] = discarded[0] + filevec[0].buffered_lines;
  435.  
  436.   /* Mark to be discarded each line that matches no line of the other file.
  437.      If a line matches many lines, mark it as provisionally discardable.  */
  438.  
  439.   for (f = 0; f < 2; f++)
  440.     {
  441.       size_t end = filevec[f].buffered_lines;
  442.       char *discards = discarded[f];
  443.       lin *counts = equiv_count[1 - f];
  444.       lin *equivs = filevec[f].equivs;
  445.       size_t many = 5;
  446.       size_t tem = end / 64;
  447.  
  448.       /* Multiply MANY by approximate square root of number of lines.
  449.      That is the threshold for provisionally discardable lines.  */
  450.       while ((tem = tem >> 2) > 0)
  451.     many *= 2;
  452.  
  453.       for (i = 0; i < end; i++)
  454.     {
  455.       lin nmatch;
  456.       if (equivs[i] == 0)
  457.         continue;
  458.       nmatch = counts[equivs[i]];
  459.       if (nmatch == 0)
  460.         discards[i] = 1;
  461.       else if (nmatch > many)
  462.         discards[i] = 2;
  463.     }
  464.     }
  465.  
  466.   /* Don't really discard the provisional lines except when they occur
  467.      in a run of discardables, with nonprovisionals at the beginning
  468.      and end.  */
  469.  
  470.   for (f = 0; f < 2; f++)
  471.     {
  472.       lin end = filevec[f].buffered_lines;
  473.       register char *discards = discarded[f];
  474.  
  475.       for (i = 0; i < end; i++)
  476.     {
  477.       /* Cancel provisional discards not in middle of run of discards.  */
  478.       if (discards[i] == 2)
  479.         discards[i] = 0;
  480.       else if (discards[i] != 0)
  481.         {
  482.           /* We have found a nonprovisional discard.  */
  483.           register lin j;
  484.           lin length;
  485.           lin provisional = 0;
  486.  
  487.           /* Find end of this run of discardable lines.
  488.          Count how many are provisionally discardable.  */
  489.           for (j = i; j < end; j++)
  490.         {
  491.           if (discards[j] == 0)
  492.             break;
  493.           if (discards[j] == 2)
  494.             ++provisional;
  495.         }
  496.  
  497.           /* Cancel provisional discards at end, and shrink the run.  */
  498.           while (j > i && discards[j - 1] == 2)
  499.         discards[--j] = 0, --provisional;
  500.  
  501.           /* Now we have the length of a run of discardable lines
  502.          whose first and last are not provisional.  */
  503.           length = j - i;
  504.  
  505.           /* If 1/4 of the lines in the run are provisional,
  506.          cancel discarding of all provisional lines in the run.  */
  507.           if (provisional * 4 > length)
  508.         {
  509.           while (j > i)
  510.             if (discards[--j] == 2)
  511.               discards[j] = 0;
  512.         }
  513.           else
  514.         {
  515.           register lin consec;
  516.           lin minimum = 1;
  517.           lin tem = length >> 2;
  518.  
  519.           /* MINIMUM is approximate square root of LENGTH/4.
  520.              A subrun of two or more provisionals can stand
  521.              when LENGTH is at least 16.
  522.              A subrun of 4 or more can stand when LENGTH >= 64.  */
  523.           while (0 < (tem >>= 2))
  524.             minimum <<= 1;
  525.           minimum++;
  526.  
  527.           /* Cancel any subrun of MINIMUM or more provisionals
  528.              within the larger run.  */
  529.           for (j = 0, consec = 0; j < length; j++)
  530.             if (discards[i + j] != 2)
  531.               consec = 0;
  532.             else if (minimum == ++consec)
  533.               /* Back up to start of subrun, to cancel it all.  */
  534.               j -= consec;
  535.             else if (minimum < consec)
  536.               discards[i + j] = 0;
  537.  
  538.           /* Scan from beginning of run
  539.              until we find 3 or more nonprovisionals in a row
  540.              or until the first nonprovisional at least 8 lines in.
  541.              Until that point, cancel any provisionals.  */
  542.           for (j = 0, consec = 0; j < length; j++)
  543.             {
  544.               if (j >= 8 && discards[i + j] == 1)
  545.             break;
  546.               if (discards[i + j] == 2)
  547.             consec = 0, discards[i + j] = 0;
  548.               else if (discards[i + j] == 0)
  549.             consec = 0;
  550.               else
  551.             consec++;
  552.               if (consec == 3)
  553.             break;
  554.             }
  555.  
  556.           /* I advances to the last line of the run.  */
  557.           i += length - 1;
  558.  
  559.           /* Same thing, from end.  */
  560.           for (j = 0, consec = 0; j < length; j++)
  561.             {
  562.               if (j >= 8 && discards[i - j] == 1)
  563.             break;
  564.               if (discards[i - j] == 2)
  565.             consec = 0, discards[i - j] = 0;
  566.               else if (discards[i - j] == 0)
  567.             consec = 0;
  568.               else
  569.             consec++;
  570.               if (consec == 3)
  571.             break;
  572.             }
  573.         }
  574.         }
  575.     }
  576.     }
  577.  
  578.   /* Actually discard the lines. */
  579.   for (f = 0; f < 2; f++)
  580.     {
  581.       char *discards = discarded[f];
  582.       lin end = filevec[f].buffered_lines;
  583.       lin j = 0;
  584.       for (i = 0; i < end; ++i)
  585.     if (minimal || discards[i] == 0)
  586.       {
  587.         filevec[f].undiscarded[j] = filevec[f].equivs[i];
  588.         filevec[f].realindexes[j++] = i;
  589.       }
  590.     else
  591.       filevec[f].changed[i] = 1;
  592.       filevec[f].nondiscarded_lines = j;
  593.     }
  594.  
  595.   free (discarded[0]);
  596.   free (equiv_count[0]);
  597. }
  598.  
  599. /* Adjust inserts/deletes of identical lines to join changes
  600.    as much as possible.
  601.  
  602.    We do something when a run of changed lines include a
  603.    line at one end and have an excluded, identical line at the other.
  604.    We are free to choose which identical line is included.
  605.    `compareseq' usually chooses the one at the beginning,
  606.    but usually it is cleaner to consider the following identical line
  607.    to be the "change".  */
  608.  
  609. static void
  610. shift_boundaries (struct file_data filevec[])
  611. {
  612.   int f;
  613.  
  614.   for (f = 0; f < 2; f++)
  615.     {
  616.       bool *changed = filevec[f].changed;
  617.       bool const *other_changed = filevec[1 - f].changed;
  618.       lin const *equivs = filevec[f].equivs;
  619.       lin i = 0;
  620.       lin j = 0;
  621.       lin i_end = filevec[f].buffered_lines;
  622.  
  623.       while (1)
  624.     {
  625.       lin runlength, start, corresponding;
  626.  
  627.       /* Scan forwards to find beginning of another run of changes.
  628.          Also keep track of the corresponding point in the other file.  */
  629.  
  630.       while (i < i_end && !changed[i])
  631.         {
  632.           while (other_changed[j++])
  633.         continue;
  634.           i++;
  635.         }
  636.  
  637.       if (i == i_end)
  638.         break;
  639.  
  640.       start = i;
  641.  
  642.       /* Find the end of this run of changes.  */
  643.  
  644.       while (changed[++i])
  645.         continue;
  646.       while (other_changed[j])
  647.         j++;
  648.  
  649.       do
  650.         {
  651.           /* Record the length of this run of changes, so that
  652.          we can later determine whether the run has grown.  */
  653.           runlength = i - start;
  654.  
  655.           /* Move the changed region back, so long as the
  656.          previous unchanged line matches the last changed one.
  657.          This merges with previous changed regions.  */
  658.  
  659.           while (start && equivs[start - 1] == equivs[i - 1])
  660.         {
  661.           changed[--start] = 1;
  662.           changed[--i] = 0;
  663.           while (changed[start - 1])
  664.             start--;
  665.           while (other_changed[--j])
  666.             continue;
  667.         }
  668.  
  669.           /* Set CORRESPONDING to the end of the changed run, at the last
  670.          point where it corresponds to a changed run in the other file.
  671.          CORRESPONDING == I_END means no such point has been found.  */
  672.           corresponding = other_changed[j - 1] ? i : i_end;
  673.  
  674.           /* Move the changed region forward, so long as the
  675.          first changed line matches the following unchanged one.
  676.          This merges with following changed regions.
  677.          Do this second, so that if there are no merges,
  678.          the changed region is moved forward as far as possible.  */
  679.  
  680.           while (i != i_end && equivs[start] == equivs[i])
  681.         {
  682.           changed[start++] = 0;
  683.           changed[i++] = 1;
  684.           while (changed[i])
  685.             i++;
  686.           while (other_changed[++j])
  687.             corresponding = i;
  688.         }
  689.         }
  690.       while (runlength != i - start);
  691.  
  692.       /* If possible, move the fully-merged run of changes
  693.          back to a corresponding run in the other file.  */
  694.  
  695.       while (corresponding < i)
  696.         {
  697.           changed[--start] = 1;
  698.           changed[--i] = 0;
  699.           while (other_changed[--j])
  700.         continue;
  701.         }
  702.     }
  703.     }
  704. }
  705.  
  706. /* Cons an additional entry onto the front of an edit script OLD.
  707.    LINE0 and LINE1 are the first affected lines in the two files (origin 0).
  708.    DELETED is the number of lines deleted here from file 0.
  709.    INSERTED is the number of lines inserted here in file 1.
  710.  
  711.    If DELETED is 0 then LINE0 is the number of the line before
  712.    which the insertion was done; vice versa for INSERTED and LINE1.  */
  713.  
  714. static struct change *
  715. add_change (lin line0, lin line1, lin deleted, lin inserted,
  716.         struct change *old)
  717. {
  718.   struct change *new = xmalloc (sizeof *new);
  719.  
  720.   new->line0 = line0;
  721.   new->line1 = line1;
  722.   new->inserted = inserted;
  723.   new->deleted = deleted;
  724.   new->link = old;
  725.   return new;
  726. }
  727.  
  728. /* Scan the tables of which lines are inserted and deleted,
  729.    producing an edit script in reverse order.  */
  730.  
  731. static struct change *
  732. build_reverse_script (struct file_data const filevec[])
  733. {
  734.   struct change *script = 0;
  735.   bool *changed0 = filevec[0].changed;
  736.   bool *changed1 = filevec[1].changed;
  737.   lin len0 = filevec[0].buffered_lines;
  738.   lin len1 = filevec[1].buffered_lines;
  739.  
  740.   /* Note that changedN[len0] does exist, and is 0.  */
  741.  
  742.   lin i0 = 0, i1 = 0;
  743.  
  744.   while (i0 < len0 || i1 < len1)
  745.     {
  746.       if (changed0[i0] | changed1[i1])
  747.     {
  748.       lin line0 = i0, line1 = i1;
  749.  
  750.       /* Find # lines changed here in each file.  */
  751.       while (changed0[i0]) ++i0;
  752.       while (changed1[i1]) ++i1;
  753.  
  754.       /* Record this change.  */
  755.       script = add_change (line0, line1, i0 - line0, i1 - line1, script);
  756.     }
  757.  
  758.       /* We have reached lines in the two files that match each other.  */
  759.       i0++, i1++;
  760.     }
  761.  
  762.   return script;
  763. }
  764.  
  765. /* Scan the tables of which lines are inserted and deleted,
  766.    producing an edit script in forward order.  */
  767.  
  768. static struct change *
  769. build_script (struct file_data const filevec[])
  770. {
  771.   struct change *script = 0;
  772.   bool *changed0 = filevec[0].changed;
  773.   bool *changed1 = filevec[1].changed;
  774.   lin i0 = filevec[0].buffered_lines, i1 = filevec[1].buffered_lines;
  775.  
  776.   /* Note that changedN[-1] does exist, and is 0.  */
  777.  
  778.   while (i0 >= 0 || i1 >= 0)
  779.     {
  780.       if (changed0[i0 - 1] | changed1[i1 - 1])
  781.     {
  782.       lin line0 = i0, line1 = i1;
  783.  
  784.       /* Find # lines changed here in each file.  */
  785.       while (changed0[i0 - 1]) --i0;
  786.       while (changed1[i1 - 1]) --i1;
  787.  
  788.       /* Record this change.  */
  789.       script = add_change (i0, i1, line0 - i0, line1 - i1, script);
  790.     }
  791.  
  792.       /* We have reached lines in the two files that match each other.  */
  793.       i0--, i1--;
  794.     }
  795.  
  796.   return script;
  797. }
  798.  
  799. /* If CHANGES, briefly report that two files differed.
  800.    Return 2 if trouble, CHANGES otherwise.  */
  801. static int
  802. briefly_report (int changes, struct file_data const filevec[])
  803. {
  804.   if (changes)
  805.     {
  806. #ifdef __riscos
  807.       char const *label0 = file_label[0] ? file_label[0] : filevec[0].unixname;
  808.       char const *label1 = file_label[1] ? file_label[1] : filevec[1].unixname;
  809. #else
  810.       char const *label0 = file_label[0] ? file_label[0] : filevec[0].name;
  811.       char const *label1 = file_label[1] ? file_label[1] : filevec[1].name;
  812. #endif
  813.  
  814.       if (brief)
  815.     message ("Files %s and %s differ\n", label0, label1);
  816.       else
  817.     {
  818.       message ("Binary files %s and %s differ\n", label0, label1);
  819.       changes = 2;
  820.     }
  821.     }
  822.  
  823.   return changes;
  824. }
  825.  
  826. /* Report the differences of two files.  */
  827. int
  828. diff_2_files (struct comparison *cmp)
  829. {
  830.   lin diags;
  831.   int f;
  832.   struct change *e, *p;
  833.   struct change *script;
  834.   int changes;
  835.  
  836.  
  837.   /* If we have detected that either file is binary,
  838.      compare the two files as binary.  This can happen
  839.      only when the first chunk is read.
  840.      Also, --brief without any --ignore-* options means
  841.      we can speed things up by treating the files as binary.  */
  842.  
  843.   if (read_files (cmp->file, files_can_be_treated_as_binary))
  844.     {
  845.       /* Files with different lengths must be different.  */
  846.       if (cmp->file[0].stat.st_size != cmp->file[1].stat.st_size
  847. #ifndef __riscos
  848.       && (cmp->file[0].desc < 0 || S_ISREG (cmp->file[0].stat.st_mode))
  849.       && (cmp->file[1].desc < 0 || S_ISREG (cmp->file[1].stat.st_mode)))
  850.       && (cmp->file[1].desc < 0 || S_ISREG (cmp->file[1].stat.st_mode))
  851. #endif
  852.          )
  853.     changes = 1;
  854.  
  855.       /* Standard input equals itself.  */
  856.       else if (cmp->file[0].desc == cmp->file[1].desc)
  857.     changes = 0;
  858.  
  859.       else
  860.     /* Scan both files, a buffer at a time, looking for a difference.  */
  861.     {
  862.       /* Allocate same-sized buffers for both files.  */
  863.       size_t lcm_max = PTRDIFF_MAX - 1;
  864.       size_t buffer_size =
  865.         buffer_lcm (sizeof (word),
  866.             buffer_lcm (STAT_BLOCKSIZE (cmp->file[0].stat),
  867.                     STAT_BLOCKSIZE (cmp->file[1].stat),
  868.                     lcm_max),
  869.             lcm_max);
  870.       for (f = 0; f < 2; f++)
  871.         cmp->file[f].buffer = xrealloc (cmp->file[f].buffer, buffer_size);
  872.  
  873.       for (;; cmp->file[0].buffered = cmp->file[1].buffered = 0)
  874.         {
  875.           /* Read a buffer's worth from both files.  */
  876.           for (f = 0; f < 2; f++)
  877.         if (0 <= cmp->file[f].desc)
  878.           file_block_read (&cmp->file[f],
  879.                    buffer_size - cmp->file[f].buffered);
  880.  
  881.           /* If the buffers differ, the files differ.  */
  882.           if (cmp->file[0].buffered != cmp->file[1].buffered
  883.           || memcmp (cmp->file[0].buffer,
  884.                  cmp->file[1].buffer,
  885.                  cmp->file[0].buffered))
  886.         {
  887.           changes = 1;
  888.           break;
  889.         }
  890.  
  891.           /* If we reach end of file, the files are the same.  */
  892.           if (cmp->file[0].buffered != buffer_size)
  893.         {
  894.           changes = 0;
  895.           break;
  896.         }
  897.         }
  898.     }
  899.  
  900.       changes = briefly_report (changes, cmp->file);
  901.     }
  902.   else
  903.     {
  904.       /* Allocate vectors for the results of comparison:
  905.      a flag for each line of each file, saying whether that line
  906.      is an insertion or deletion.
  907.      Allocate an extra element, always 0, at each end of each vector.  */
  908.  
  909.       size_t s = cmp->file[0].buffered_lines + cmp->file[1].buffered_lines + 4;
  910.       bool *flag_space = zalloc (s * sizeof *flag_space);
  911.       cmp->file[0].changed = flag_space + 1;
  912.       cmp->file[1].changed = flag_space + cmp->file[0].buffered_lines + 3;
  913.  
  914.       /* Some lines are obviously insertions or deletions
  915.      because they don't match anything.  Detect them now, and
  916.      avoid even thinking about them in the main comparison algorithm.  */
  917.  
  918.       discard_confusing_lines (cmp->file);
  919.  
  920.       /* Now do the main comparison algorithm, considering just the
  921.      undiscarded lines.  */
  922.  
  923.       xvec = cmp->file[0].undiscarded;
  924.       yvec = cmp->file[1].undiscarded;
  925.       diags = (cmp->file[0].nondiscarded_lines
  926.            + cmp->file[1].nondiscarded_lines + 3);
  927.       fdiag = xmalloc (diags * (2 * sizeof *fdiag));
  928.       bdiag = fdiag + diags;
  929.       fdiag += cmp->file[1].nondiscarded_lines + 1;
  930.       bdiag += cmp->file[1].nondiscarded_lines + 1;
  931.  
  932.       /* Set TOO_EXPENSIVE to be approximate square root of input size,
  933.      bounded below by 256.  */
  934.       too_expensive = 1;
  935.       for (;  diags != 0;  diags >>= 2)
  936.     too_expensive <<= 1;
  937.       too_expensive = MAX (256, too_expensive);
  938.  
  939.       files[0] = cmp->file[0];
  940.       files[1] = cmp->file[1];
  941.  
  942.       compareseq (0, cmp->file[0].nondiscarded_lines,
  943.           0, cmp->file[1].nondiscarded_lines, minimal);
  944.  
  945.       free (fdiag - (cmp->file[1].nondiscarded_lines + 1));
  946.  
  947.       /* Modify the results slightly to make them prettier
  948.      in cases where that can validly be done.  */
  949.  
  950.       shift_boundaries (cmp->file);
  951.  
  952.       /* Get the results of comparison in the form of a chain
  953.      of `struct change's -- an edit script.  */
  954.  
  955.       if (output_style == OUTPUT_ED)
  956.     script = build_reverse_script (cmp->file);
  957.       else
  958.     script = build_script (cmp->file);
  959.  
  960.       /* Set CHANGES if we had any diffs.
  961.      If some changes are ignored, we must scan the script to decide.  */
  962.       if (ignore_blank_lines || ignore_regexp.fastmap)
  963.     {
  964.       struct change *next = script;
  965.       changes = 0;
  966.  
  967.       while (next && changes == 0)
  968.         {
  969.           struct change *this, *end;
  970.           lin first0, last0, first1, last1;
  971.  
  972.           /* Find a set of changes that belong together.  */
  973.           this = next;
  974.           end = find_change (next);
  975.  
  976.           /* Disconnect them from the rest of the changes, making them
  977.          a hunk, and remember the rest for next iteration.  */
  978.           next = end->link;
  979.           end->link = 0;
  980.  
  981.           /* Determine whether this hunk is really a difference.  */
  982.           if (analyze_hunk (this, &first0, &last0, &first1, &last1))
  983.         changes = 1;
  984.  
  985.           /* Reconnect the script so it will all be freed properly.  */
  986.           end->link = next;
  987.         }
  988.     }
  989.       else
  990.     changes = (script != 0);
  991.  
  992.       if (brief)
  993.     changes = briefly_report (changes, cmp->file);
  994.       else
  995.     {
  996.       if (changes | !no_diff_means_no_output)
  997.         {
  998.           /* Record info for starting up output,
  999.          to be used if and when we have some output to print.  */
  1000. #ifdef __riscos
  1001.           setup_output (file_label[0] ? file_label[0] : cmp->file[0].unixname,
  1002.                 file_label[1] ? file_label[1] : cmp->file[1].unixname,
  1003.                 cmp->parent != 0);
  1004. #else
  1005.           setup_output (file_label[0] ? file_label[0] : cmp->file[0].name,
  1006.                 file_label[1] ? file_label[1] : cmp->file[1].name,
  1007.                 cmp->parent != 0);
  1008. #endif
  1009.  
  1010.           switch (output_style)
  1011.         {
  1012.         case OUTPUT_CONTEXT:
  1013.           print_context_script (script, 0);
  1014.           break;
  1015.  
  1016.         case OUTPUT_UNIFIED:
  1017.           print_context_script (script, 1);
  1018.           break;
  1019.  
  1020.         case OUTPUT_ED:
  1021.           print_ed_script (script);
  1022.           break;
  1023.  
  1024.         case OUTPUT_FORWARD_ED:
  1025.           pr_forward_ed_script (script);
  1026.           break;
  1027.  
  1028.         case OUTPUT_RCS:
  1029.           print_rcs_script (script);
  1030.           break;
  1031.  
  1032.         case OUTPUT_NORMAL:
  1033.           print_normal_script (script);
  1034.           break;
  1035.  
  1036.         case OUTPUT_IFDEF:
  1037.           print_ifdef_script (script);
  1038.           break;
  1039.  
  1040.         case OUTPUT_SDIFF:
  1041.           print_sdiff_script (script);
  1042.           break;
  1043.  
  1044.         default:
  1045.           abort ();
  1046.         }
  1047.  
  1048.           finish_output ();
  1049.         }
  1050.     }
  1051.  
  1052.       free (cmp->file[0].undiscarded);
  1053.  
  1054.       free (flag_space);
  1055.  
  1056.       for (f = 0; f < 2; f++)
  1057.     {
  1058.       free (cmp->file[f].equivs);
  1059.       free (cmp->file[f].linbuf + cmp->file[f].linbuf_base);
  1060.     }
  1061.  
  1062.       for (e = script; e; e = p)
  1063.     {
  1064.       p = e->link;
  1065.       free (e);
  1066.     }
  1067.  
  1068.       if (! ROBUST_OUTPUT_STYLE (output_style))
  1069.     for (f = 0; f < 2; ++f)
  1070.       if (cmp->file[f].missing_newline)
  1071.         {
  1072.           error (0, 0, "%s: %s\n",
  1073.              file_label[f] ? file_label[f] : cmp->file[f].name,
  1074.              _("No newline at end of file"));
  1075.           changes = 2;
  1076.         }
  1077.     }
  1078.  
  1079.   if (cmp->file[0].buffer != cmp->file[1].buffer)
  1080.     free (cmp->file[0].buffer);
  1081.   free (cmp->file[1].buffer);
  1082.  
  1083.   return changes;
  1084. }
  1085.